package xiang.weiyu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xiang.weiyu.dto.DishDto;
import xiang.weiyu.mapper.DishMapper;
import xiang.weiyu.pojo.Dish;
import xiang.weiyu.pojo.DishFlavor;
import xiang.weiyu.service.DishFlavorService;
import xiang.weiyu.service.DishService;

import java.util.List;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    private DishFlavorService dishFlavorService;

    /**
     * 新增菜品,同时插入菜品口味,需要操作两张表,dish和dish_flavor
     *
     * @param dishDto
     */
    @Override
    @Transactional//多表操作,开启事务
    public void saveWithFlover(DishDto dishDto) {
        //1.保存菜品信息到dish表中,因为DishDto继承Dish类可以直接保存
        this.save(dishDto);
        //2.保存菜品口味到dish_flavor表中
        //2.1此时dish_flavor只保存了口味数据和口味名称,还需要保存上对应的菜品id
        //dishFlavorService.saveBatch(dishDto.getFlavors());
        //2.2获得口味数据表集合
        List<DishFlavor> flavors = dishDto.getFlavors();
        //2.3获得口味数据对应的菜品id
        Long dishId = dishDto.getId();
        //2.4遍历集合，将菜品id赋予每一个表单数据
        flavors.forEach(dishFlavor -> dishFlavor.setDishId(dishId));
        //2.5现在再保存菜品口味到dish_flavor表中
        dishFlavorService.saveBatch(dishDto.getFlavors());
    }

    /**
     * 根据菜品id查询菜品及口味信息
     *
     * @param id
     * @return
     */
    @Override
    public DishDto getByDishId(Long id) {
        DishDto dishDto = new DishDto();
        //查询菜品信息,dish表
        Dish dish = this.getById(id);
        //调用Xxx方法,将菜品信息存入DishDto
        BeanUtils.copyProperties(dish, dishDto);
        //查询口味信息,按照菜品id查询dish_flavor表口味信息集合
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId, id);
        List<DishFlavor> list = dishFlavorService.list(queryWrapper);
        dishDto.setFlavors(list);
        return dishDto;
    }

    /**
     * 修改菜品
     *
     * @param dishDto
     */
    @Override
    @Transactional//多表操作,开启事务
    public void updateDish(DishDto dishDto) {
        this.updateById(dishDto);
        //获得原来菜品的id,通过id删除dish_flavor口味表关联的数据
        Long dishId = dishDto.getId();
        LambdaQueryWrapper<DishFlavor> dishFlavorWrapper = new LambdaQueryWrapper<>();
        dishFlavorWrapper.eq(DishFlavor::getDishId, dishId);
        dishFlavorService.remove(dishFlavorWrapper);
        //保存菜品信息到dish表中,先获得口味数据表集合
        List<DishFlavor> flavors = dishDto.getFlavors();
        //遍历集合，将菜品id赋予每一个表单数据
        flavors.forEach(dishFlavor -> dishFlavor.setDishId(dishId));
        //现在再保存菜品口味到dish_flavor表中
        dishFlavorService.saveBatch(dishDto.getFlavors());
    }
}
